package com.qianxunclub.context.service;

import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.qianxunclub.context.Model.PageParam;
import com.qianxunclub.util.PageDataResponse;
import com.qianxunclub.util.ReturnCode;
import lombok.extern.log4j.Log4j;


/**
 * Created by zhangbin on 2017/3/7.
 */
@Log4j
public abstract class AbstractService<ModelT extends Model,MapperT extends BaseMapper<ModelT>> extends ServiceImpl<MapperT,ModelT> implements IService<ModelT> {


    public PageDataResponse<ModelT> list(PageParam param,EntityWrapper<ModelT> ew){
        Page<ModelT> page = getPage(param,ew);
        return returnResponse(page);
    }

    private Page<ModelT> getPage(PageParam param,EntityWrapper<ModelT> ew){
        Page<ModelT> page = new Page<ModelT>();
        if (null != param && null != param.getOffset() && null != param.getLimit()) {
            page.setCurrent(param.getOffset());
            page.setSize(param.getLimit());
        } else {
            page.setCurrent(1);
            page.setSize(this.selectCount(ew));
        }
        page = this.selectPage(page, ew);
        return page;
    }

    private PageDataResponse<ModelT> returnResponse(Page<ModelT> page){
        PageDataResponse<ModelT> pageDataResponse = new PageDataResponse<ModelT>();
        pageDataResponse.setReturn(ReturnCode.CODE_1000);
        pageDataResponse.setPageData(page.getRecords());
        pageDataResponse.setLimit(page.getLimit());
        pageDataResponse.setOffset(page.getOffset());
        pageDataResponse.setTotal(page.getTotal());
        return pageDataResponse;
    }
}
